'use client';

import React, { useState, useEffect, useRef } from 'react';
import { Spin, Alert, Button } from 'antd';
import { LoadingOutlined, ReloadOutlined } from '@ant-design/icons';
import AdminLayout from '../AdminLayout';
import styles from './AdvancedFeatures.module.scss';
import { useRouter } from 'next/navigation';

interface Config {
  sdWebUI: {
    baseUrl: string;
    defaultPort: number;
  };
  api: {
    baseUrl: string;
    timeout: number;
  };
  version: string;
  title: string;
}

const AdvancedFeatures: React.FC = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [iframeKey, setIframeKey] = useState(0);
  const [config, setConfig] = useState<Config | null>(null);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const router = useRouter();

  // 获取配置
  useEffect(() => {
    const loadConfig = async () => {
      try {
        const response = await fetch('/api/config');
        if (response.ok) {
          const configData = await response.json();
          setConfig(configData);
        } else {
          throw new Error('Failed to load configuration');
        }
      } catch (error) {
        console.error('Error loading config:', error);
        setLoadError('无法加载配置信息');
      }
    };

    loadConfig();
  }, []);

  useEffect(() => {
    fetch('/api/license/status').then(async (res) => {
      const result = await res.json();
      if (result.status !== 200) {
        router.push('/');
      }
    }).catch(() => {
      router.push('/');
    });
  }, []);

  // 配置加载完成后初始化iframe
  useEffect(() => {
    if (config) {
      setIsLoading(true);
      setLoadError(null);
      setIframeKey(prev => prev + 1);
    }
  }, [config]);

  const handleIframeLoad = () => {
    setIsLoading(false);
    setLoadError(null);
  };

  const handleIframeError = () => {
    setIsLoading(false);
    setLoadError('无法连接到SD WebUI服务，请检查服务是否已启动');
  };

  const handleRetry = () => {
    setIsLoading(true);
    setLoadError(null);
    setIframeKey(prev => prev + 1);
  };

  // 如果配置未加载，显示加载状态
  if (!config) {
    return (
      <AdminLayout pageTitle="高级功能">
        <div className={styles.container}>
          <div className={styles.iframeContainer}>
            <div className={styles.loadingOverlay}>
              <Spin 
                indicator={<LoadingOutlined style={{ fontSize: 48, color: '#00ff00' }} spin />}
                size="large"
              />
              <div className={styles.loadingText}>正在加载配置...</div>
            </div>
          </div>
        </div>
      </AdminLayout>
    );
  }

  const sdWebUIUrl = `${config.sdWebUI.baseUrl}?__theme=dark`;

  return (
    <AdminLayout pageTitle="高级功能">
      <div className={styles.container}>
        <div className={styles.iframeContainer}>
          {/* 加载状态 */}
          {isLoading && (
            <div className={styles.loadingOverlay}>
              <Spin 
                indicator={<LoadingOutlined style={{ fontSize: 48, color: '#00ff00' }} spin />}
                size="large"
              />
              <div className={styles.loadingText}>正在加载高级功能...</div>
            </div>
          )}

          {/* 错误提示 */}
          {loadError && (
            <div className={styles.errorOverlay}>
              <Alert
                message="连接错误"
                description={loadError}
                type="error"
                showIcon
                className={styles.errorAlert}
                action={
                  <Button 
                    type="primary" 
                    icon={<ReloadOutlined />}
                    onClick={handleRetry}
                    className={styles.retryButton}
                  >
                    重试
                  </Button>
                }
              />
            </div>
          )}

          <iframe
            key={iframeKey}
            ref={iframeRef}
            src={sdWebUIUrl}
            className={styles.iframe}
            title="高级功能"
            allowFullScreen
            scrolling="auto"
            onLoad={handleIframeLoad}
            onError={handleIframeError}
          />
        </div>
      </div>
    </AdminLayout>
  );
};

export default AdvancedFeatures; 